<?php

namespace ToolKit\Robot\Engine;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use ToolKit\Exceptions\RemoteException;
use ToolKit\Exceptions\ValidationException;

class QywechatEngine implements RobotEngineInterface
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client();
    }

    /**
     * @param $config
     * @param $contentType
     * @param $content
     * @return bool|mixed
     * @throws GuzzleException
     * @throws RemoteException
     * @throws ValidationException
     */
    public function send($config, $contentType, $content)
    {
        $hookUrl = $this->parseConfig($config);
        switch ($contentType) {
            case 'text':
                $this->text($hookUrl, $content);
                break;
            default:
                throw new ValidationException('不支持的消息类型 content_type:' . $contentType);
        }
        return true;
    }

    /**
     * User: Luw
     * Datetime: 2020/7/2 15:07
     * @param $config
     * @return mixed
     * @throws ValidationException
     */
    protected function parseConfig($config)
    {
        if (!isset($config['hook_url']) || empty($config['hook_url'])) {
            throw new ValidationException('hook_url 是必选项');
        }
        return $config['hook_url'];
    }

    /**
     * @param $hookUrl
     * @param $content
     * @return bool
     * @throws GuzzleException
     * @throws RemoteException
     */
    protected function text($hookUrl, $content)
    {
        $response = $this->client->request('post', $hookUrl, [
            'json' => [
                'msgtype' => 'text',
                'text' => [
                    'content' => $content,
                ]
            ]
        ]);
        if ($response->getStatusCode() != 200) {
            throw new RemoteException('请求' . $hookUrl . '地址失败 status_code:' . $response->getStatusCode());
        }
        return true;
    }
}